﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CustomNumberText : MonoBehaviour {

    SimpleNumberFont snf;
    Dictionary<string, Sprite> dic = new Dictionary<string, Sprite>();
    public string numFontName;
    void Awake ()
    {
        snf = Resources.Load<SimpleNumberFont>("NumberFont/"+ numFontName);
        if (snf != null)
        {
            for (int i = 0; i < snf.key.Length; i++)
            {
                dic[snf.key[i].key] = snf.key[i].sprite;
            }
        }
    }

    string textContent;
    public string text
    {
        set
        {
            textContent = value;
            OnSetText(textContent);
        }
        get {
            return textContent;
        }
    }

    void OnSetText(string s)
    {
        GameObject prefab;
        if (transform.childCount == 0)
        {
            prefab = new GameObject("num");
            prefab.AddComponent<Image>();
        }
        else
        {
            prefab = transform.GetChild(0).gameObject;
        }
        for (int i = 0; i < s.Length; i++)
        {
            GameObject item = null;
            if (i < transform.childCount)
            {
                item = transform.GetChild(i).gameObject;
            }
            else
            {
                item = GameObject.Instantiate<GameObject>(prefab);
                item.name = prefab.name;
                item.transform.SetParent(transform,false);
            }
            Image img = item.GetComponent<Image>();
            string sk = s[i].ToString();
            if (dic.ContainsKey(sk))
            {
                img.sprite = dic[sk];
            }
            img.SetNativeSize();
        }
    }
}
